package com.cardbaobao.cardbabyclient.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.model.old.Result;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.controller.BroadcastController;
import com.cardbaobao.cardbabyclient.model.UserInfo;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.utils.BitmapUtil;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * 个人资料
 * 2016/12/26 19:44
 */
public class AvatarNickNameActivity extends BaseActivity implements View.OnClickListener {

    private final int NICK_NAME_REQUEST_CODE = 1001;

    private static final int GET_PHOTO_REQUEST_CODE = 2002;
    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.user_name_layout)
    LinearLayout user_name_layout;
    /**
     * 修改头像跳转
     */
    @BindView(R.id.user_avatar_layout)
    LinearLayout mLLUserAvatar;
    /**
     * 头像显示
     */
    @BindView(R.id.user_avatar)
    ImageView mIvUserAvatar;

    @BindView(R.id.user_nick)
    TextView user_nick;

    private UserInfo mUser;

    @Override
    protected void initView(Bundle savedInstanceState) {
        ImmersionBar.with(this).statusBarDarkFont(true,Constant.STATUS_BAR_FONT_ALPHA).init();
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mCurrentPageId= Self.Page.app_personal_information_page;

    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        user_name_layout.setOnClickListener(this);
        mLLUserAvatar.setOnClickListener(this);
        initView();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_avatar_nick_name;
    }

    @Override
    protected void onResume() {
        super.onResume();
        UmengEventUtils.pageEvent(mContext,
                ApplicationHelper.getApplicationContext().getString(R.string.event_0x016));
        GoogleAnalyticsUtil.setScreenName(Google.PERSONAL_INFO_MINE);
    }

    private void initView() {
        mUser = mApplication.getUser();
        if (mUser == null) {
            finish();
            return;
        }
        ImageLoaderUtil.displayImageWithPlaceHolder(
                URLUtil.CBB_IMG_URL + mUser.getHeadImages(),
                mIvUserAvatar,
                R.mipmap.img_default_avatar,
                DensityUtil.dp2px(6)
        );
        user_nick.setText(mUser.getUserName());
    }

    private void updateNickNameData(final String nickName) {
        showProgressDialog(false);
        Observable<String> observable=
                Api.updateUserNickName(String.valueOf(mApplication.getUser().getID()),
                        nickName);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToastOnScreenCenter(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject object = JSON.parseObject(s);
                if (object.getIntValue("code") == 1) {
                    user_nick.setText(nickName);
                    mApplication.getUser().setUserName(nickName);
                    new BroadcastController(mContext).notifyUserLogin();
                }
                ToastUtil.showToastOnScreenCenter(object.getString("msg"));
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_name_layout:
                //修改昵称
                Intent intent = new Intent(mContext, NicknameUpdateActivity.class);
                intent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                intent.putExtra("content", mUser.getUserName());
                this.startActivityForResult(intent, NICK_NAME_REQUEST_CODE);
                break;
            case R.id.user_avatar_layout:
                //修改头像
                SelfUtils.buriedClickData(Self.Action.app_click_modify_user_avatar,
                        Self.Action.app_click_modify_user_avatar_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                initIntent();
                mIntent.setClass(mContext, GetPictureActivity.class);
                mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                startActivityForResult(mIntent, GET_PHOTO_REQUEST_CODE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == NICK_NAME_REQUEST_CODE) {//修改昵称
                if (data != null) {
                    String nickName = data.getStringExtra("content");
                    if (!nickName.equals(mUser.getUserName())) {
                        updateNickNameData(nickName);
                    }
                }
            } else if (requestCode == GET_PHOTO_REQUEST_CODE) {
                //更改头像
                if (data != null) {
                    String picture_url = data.getStringExtra("picture_url");//相册头像地址
                    setUserHeader(picture_url);//设置头像显示
                    uploadUserHeader(picture_url);
                }
            }
        }
    }

    /**
     *  服务器上传头像
     *
     * @param headerPath 本地头像地址
     */
    private void uploadUserHeader(String headerPath) {
        Observable<String> observable=
                Api.updateUserAvatar(String.valueOf(mApplication.getUser().getID()),
                        headerPath);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast("更新头像失败");
            }

            @Override
            public void onNext(String s) {
                Result result = JsonUtil.getResult(s, Result.class);
                if (null != result) {
                    if (result.getResult().equals(Result.SUCCESS)) {
                        //上传成功
                        ToastUtil.showToastOnScreenCenter(result.getMsg());
                        UserInfo userInfo = mApplication.getUser();
                        if (userInfo != null) {
                            userInfo.setHeadImages(result.getUrl());//设置用户头像
                        }
                    } else {
                        //上传失败
                        ToastUtil.showToastOnScreenCenter(result.getMsg());
                    }
                }
            }
        });
    }

    /**
     *  设置用户头像
     *
     * @param imgPath 本地头像地址
     */
    private void setUserHeader(String imgPath) {
        int imgWidth = DensityUtil.dp2px(48);
        Bitmap bitmap = BitmapUtil.getSmallBitmap(imgPath, imgWidth, imgWidth);
        if (bitmap != null) {
            mIvUserAvatar.setImageBitmap(bitmap);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            mApplication.setUser(mApplication.getUser());//保存用户信息到本地
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
